<template>
  <div class="uppy-upload-box">
    <div class="uppy-upload-area" @dragover.prevent @drop.prevent="handleDrop" @click="selectFile">
      <img src="@/assets/video.png" class="uppy-upload-icon" />
      <div>
        <input ref="fileInput" type="file" accept=".mp4" @change="handleFileSelect" style="display: none" />
      </div>
    </div>

    <!-- 上传成功后展示视频 -->
    <div class="preview" v-if="videoUrl || itemUrl">
      <video
        :src="videoUrl?$videoFull(videoUrl):$videoFull(itemUrl)"
        controls
        height="100"
        style="border: 1px solid #ccc; border-radius: 6px;"
      ></video>
    </div>
  </div>
</template>

<script>
import Uppy from '@uppy/core'
import XHRUpload from '@uppy/xhr-upload'
import { nanoid } from 'nanoid'

export default {
  name: 'UppyUploader',
  props: {
    uploadUrl: {
      type: String,
      default: ''
    },

    itemUrl: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      videoUrl : this.itemUrl,
      uppy: null,
    }
  },
  mounted() {
    this.uppy = new Uppy({
      restrictions: {
        maxFileSize: 200 * 1024 * 1024,
        allowedFileTypes: ['.mp4'],
        maxNumberOfFiles: 1
      },
      autoProceed: true
    }).use(XHRUpload, {
      endpoint: this.uploadUrl,
      fieldName: 'file'
    })

    this.uppy.on('upload-success', (file, response) => {
      const data = response.body.data
      console.log('---response---',response)
      this.videoUrl = data.url
      this.$emit('videoUploadCallback', data)
    })
  },
  beforeDestroy() {
    this.uppy && this.uppy.close()
  },
  methods: {
    selectFile() {
      this.$refs.fileInput.click()
    },
    handleFileSelect(e) {
      const file = e.target.files[0]
      if (file) {
        this.addToUppy(file)
      }
    },
    handleDrop(e) {
      const file = e.dataTransfer.files[0]
      if (file) {
        this.addToUppy(file)
      }
    },
    addToUppy(file) {
      this.uppy.cancelAll()
      this.uppy.addFile({
        name: file.name,
        type: file.type,
        data: file,
        source: 'manual',
        id: nanoid()
      })
    }
  }
}
</script>

<style scoped>
  .uppy-upload-box{
    display: flex;
    align-items: center;
    padding-left: 10px;
  }
  .uppy-upload-area {
    border: 2px dashed #dcdfe6;
    border-radius: 6px;
    width: 100px;
    height: 100px;
    background-color: #fafafa;
    text-align: center;
    cursor: pointer;
    transition: border-color 0.3s;
    display:flex;
    justify-content:center;
    align-items: center;
  }
   .uppy-upload-icon{
     width: 20px;
     height: 20px;
   }

  .uppy-upload-area:hover {
    border-color: #409EFF;
  }

  .desc {
    color: #909399;
    font-size: 14px;
  }

  .preview {

    max-height: 100px;
    padding-left: 20px;

  }

  .thumb {
    max-height: 100px;
    border: 1px solid #dcdfe6;

  }
</style>
